import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css' 
import { useStore } from '@/store'
import {observer} from 'mobx-react-lite'
import { useEffect, useRef, useState } from 'react'
import { http } from '@/utils'

const { Option } = Select

const Publish = () => {

  const {channelStore} = useStore()
  // 存放上传图片的列表
  const [fileList, setFileList] = useState([])
  // 使用useRef声明一个暂存仓库
  const cacheIMgList = useRef()
  const onUploadChange = ({fileList}) =>{
    console.log(fileList);
    // 采取受控的写法，在最后一次log里response
    // 最终 react state fileList中存放的数据有response.data.url
    // 关键位置: 需要做数据格式化
    const formatList = fileList.map(file => {
      // 上传完毕
      if(file.response) {
        return {
          url: file.response.data.url
        }
      }
      return file
    })
    setFileList(formatList)
    // 同事吧图片列表存入仓库一份
    cacheIMgList.current = formatList
  }


  // 切换图片
  const [imgCount, setImgCount] = useState(1)
  const radioChange = (e) =>{
    // console.log(e.target.value);
    // 判断依据要采取原始值  不采取经过useState方法修改之后的数据，无法同步获取修改之后的值
    const reaValue = e.target.value
    setImgCount(reaValue)
    // 从仓库里面取对应的图片数量 交给我们用来渲染图片列表的fileList
    // 通过调用setFileList
    // 无图模式
    if (cacheIMgList.current.length === 0) {
      return false
    }
    if(reaValue === 1) {
      const img = cacheIMgList.current ? cacheIMgList.current[0]:[]
      setFileList([img])
    }else if (reaValue === 3) {
      setFileList(cacheIMgList.current)
    }
  }

  // 提交表单
  const navigate = useNavigate()
  const onFinish = async (values) =>{
    // console.log(values);
    // 二次处理
    const {channel_id, content, title, type} = values
    // console.log(fileList);
    const params = {
      channel_id, content, title, type,
      cover: {
        type: type,
        images: fileList.map(item =>item.url)
      }
    }
    if (id) {
      await http.put(`/mp/articles/${id}?draft=false`, params)
    } else {
      await http.post('/mp/articles?draft=false', params)
    }
    // 跳转列表 提示用户
    navigate('/article')
    message.success(`${id ? '更新成功' : '发布成功'}`)
  }

  // 编辑功能
  // 文案适配 
  const [params] = useSearchParams()
  const id =  params.get("id")
  // console.log(id);
  // 数据回填 id调用接口 1.表单回填 2.暂存列表 3.Upload组件fileList
  const form = useRef(null)
  useEffect(() =>{
    const loadDetail = async () =>{
      const res =  await http.get(`/mp/articles/${id}`)
      const data = res.data.data
      // console.log(res);
      // 表单数据回填
      form.current.setFieldsValue({...data, type: data.cover.type})
      // 调用 setFileList 方法 回填upload
      const formatImgList = data.cover.images.map(url =>({url}))
      setFileList(formatImgList)
      // 暂存列表也存一份
      cacheIMgList.current = formatImgList
      setImgCount(data.cover.type)
    }
    if(id) {
      loadDetail()
      console.log(form);
    }
  }, [id])

  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id?"编辑":"发布"}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 , content: "this is content"}}
          onFinish={onFinish}
          ref={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {
                channelStore.channelList.map(item =>(
                  <Option value={item.id} key={item.id}>{item.name}</Option>
                ))
              }
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={radioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 && (
                <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUploadChange}
                multiple = {imgCount > 1}
                maxCount = {imgCount}
                >
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
                </Upload>
            )}
            
          </Form.Item>
          {/* 这里的富文本 已经被Form.Item控制 */}
          {/* 它的输入内容 将会在 onFinished中收集起来 */}
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
              {id?"更新文章":"发布文章"}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Publish)